package controllers;

import java.util.Collections;
import java.util.List;

import models.Establishment;
import models.Location;
import models.Menu;
import models.MenuItem;
import models.MenuSection;
import models.Place;
import play.mvc.Controller;

public class EatAtSeatRest extends Controller {
    public static void places(Location location) {
    	List<Place> places = Collections.EMPTY_LIST;
    	
    	if (location !=  null && location.getLatitude() != null && location.getLongitude() != null) {
        	double latitude = Math.toRadians(location.getLatitude()); 
        	double longitude = Math.toRadians(location.getLongitude());
        	
        	places = Place.find("FROM Place p WHERE acos(sin(p.location.latitude) * sin(?) + cos(p.location.latitude) * cos(?) * cos(p.location.longitude - (?))) * ? <= ?", 
    				latitude, 
    				latitude,
    				longitude,
    				Location.EARTH_RADIUS,
    				Location.MAX_DISTANCE).fetch();
    	} else {
    		places = Place.findAll();
    	}
    	
    	renderJSON(places, new Place.PlacesJsonSerializer());
    }
    
    public static void place(Long id) {
    	renderJSON(Place.findById(id), new Place.PlaceJsonSerializer());
    }
    
    public static void establishments(Long id) {
    	List<Establishment> establishments = Establishment.find("byPlace.Id", id).fetch();
    	
    	renderJSON(establishments, new Establishment.EstablishmentsJsonSerializer());
    }
    
    public static void establishment(Long id) {
    	Establishment establishment = Establishment.findById(id);
    	renderJSON(establishment, new Establishment.EstablishmentJsonSerializer());
    }
    
    public static void menu(Long id) {
    	Menu menu = Menu.find("byEstablishment.Id", id).first();
    	renderJSON(menu, new Menu.MenuJsonSerializer());
    }
    
    public static void sections(Long id) {
    	List<MenuSection> sections = MenuSection.find("byMenu.Id", id).fetch();
    	renderJSON(sections, new MenuSection.SectionsJsonSerializer());
    }
    
    public static void section(Long id) {
    	MenuSection section = MenuSection.findById(id);
    	renderJSON(section, new MenuSection.SectionJsonSerializer());
    }
    
    public static void items(Long id) {
    	List<MenuItem> items = MenuItem.find("bySection.Id", id).fetch();
    	renderJSON(items, new MenuItem.ItemsJsonSerializer());
    }
    
    public static void item(Long id) {
    	MenuItem item = MenuItem.findById(id);
    	renderJSON(item, new MenuItem.ItemJsonSerializer());
    }
}